package com.azzcs.mvc.rm;

import com.azzcs.mvc.mav.Model;
import com.azzcs.mvc.mav.ModelAndView;
import com.azzcs.mvc.mav.SimpleModel;
import com.azzcs.mvc.servlet.HandlerAdapter;
import com.azzcs.mvc.servlet.HandlerMethod;
import com.azzcs.spring.anno.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @Author: wzg
 * @Date: 2020/12/28 下午5:45
 */
@Component
public class RequestMappingHandlerAdapter implements HandlerAdapter {
    @Override
    public boolean support(Object handler) {
        return handler instanceof HandlerMethod;
    }

    @Override
    public ModelAndView handler(HttpServletRequest req, HttpServletResponse resp, HandlerMethod handler) {
        Model model = new SimpleModel();
        Object[] parameter = getParameter(req,handler,model);
        Object bean = handler.getBean();
        Method method = handler.getMethod();
        String viewName = null;
        try {
            Object result = method.invoke(bean, parameter);
            if(result instanceof ModelAndView){
                return (ModelAndView)result;
            }else if(result instanceof String){
                viewName = (String) result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView(model,viewName);
    }

    private Object[] getParameter(HttpServletRequest req, HandlerMethod handler, Model model) {
        Method method = handler.getMethod();
        Parameter[] parameters = method.getParameters();
        if(parameters == null || parameters.length == 0){
            return null;
        }
        Object[] resultParameters = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            if(parameter.getType().isAssignableFrom(Model.class)){
                resultParameters[i] = model;
                continue;
            }
            String name = parameters[i].getName();
            String value = req.getParameter(name);
            resultParameters[i] = value;
        }
        return resultParameters;
    }
}
